package com.example.common.networkutil

import com.example.common.R
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.example.common.tools.LogUtils
import com.example.common.tools.TooldUtils
import com.example.common.tools.isNotEmpty
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.util.concurrent.TimeUnit

class RetrofitUtil {

    private var retrofit: Retrofit? = null
    private var tokenRetrofit: Retrofit? = null


    internal var gson: Gson? = null

    fun initGson() {
        if (gson == null) {
            val builder = GsonBuilder()
            gson = builder.setPrettyPrinting()
                    .disableHtmlEscaping()
                    .setDateFormat("yyyy-MM-dd:HH-mm:ss")
                    .serializeNulls()
                    .create()
        }
    }

    constructor() {
        initGson()
    }

    @Synchronized
    fun getRetrofit(baseUrl: String): Retrofit {
        if (retrofit == null) {
            init(baseUrl)
        }
        return retrofit!!
    }

    @Synchronized
    fun getTokenRetrofit(baseUrl: String, token: String): Retrofit {
        if (tokenRetrofit == null) {
            init(baseUrl, token)
        }
        return tokenRetrofit!!
    }


    @Synchronized
    fun init(baseUrl: String, token: String = "") {
        if (token.isNotEmpty()) {
            tokenRetrofit = Retrofit.Builder().client(getOkHttpClent(token)).baseUrl(baseUrl)
                    .addConverterFactory(MyConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())  //添加适配器
                    .build()
        } else {
            retrofit = Retrofit.Builder().client(getOkHttpClent(token)).baseUrl(baseUrl)
                    .addConverterFactory(MyConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())  //添加适配器
                    .build()
        }
    }

    fun getInterceptor(token: String): Interceptor {
        return object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                val request = if (token.isNotEmpty()) {
                    LogUtils.eLog("token", "token  ------》  $token")
                    chain.request().newBuilder()
                            .addHeader(
                                    "Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8"
                            )
                            .addHeader("Token", token)
                            .build()
                } else {
                    chain.request().newBuilder()
                            .addHeader(
                                    "Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8"
                            )
                            .build()
                }
                return chain.proceed(request)
            }

        }
    }


    fun getOkHttpClent(token: String): OkHttpClient {
        val httpLoggingInterceptor = HttpLoggingInterceptor(logger())
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        val build = OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)   //连接超时
                .readTimeout(30, TimeUnit.SECONDS)      //读取超时
                .writeTimeout(90, TimeUnit.SECONDS)      //
                .addNetworkInterceptor(getInterceptor(token))
                .addInterceptor(httpLoggingInterceptor)
        //信任证书
        HTTPSCerUtils.setCertificateAssets(TooldUtils.getApplication()!!,build,"server.crt")

        return build.build()
    }

    class logger : HttpLoggingInterceptor.Logger {

        override fun log(message: String) {
            LogUtils.eLog("Net:", message)

        }
    }


    fun destroyTokenRetrofit() {
        tokenRetrofit = null
    }
}

